from PyQt5.QtWidgets import QDialog, QVBoxLayout, QHBoxLayout, QTableWidget, QTableWidgetItem
from PyQt5.QtCore import Qt
from qfluentwidgets import PrimaryPushButton, InfoBar, InfoBarPosition, SubtitleLabel
import os


class MatrixEditorDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('矩阵编辑器')
        self.resize(900, 800)
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout(self)

        # 添加标题
        title = SubtitleLabel('障碍物编辑器', self)
        layout.addWidget(title, alignment=Qt.AlignCenter)

        # 创建矩阵编辑器
        self.matrix_editor = QTableWidget(self)
        self.matrix_editor.setSizeAdjustPolicy(QTableWidget.AdjustToContents)
        self.matrix_editor.cellClicked.connect(self.toggle_obstacle)
        self.matrix_editor.horizontalHeader().hide()

        # 移除设置垂直表头样式的代码
        layout.addWidget(self.matrix_editor)

        # 添加按钮
        btn_layout = QHBoxLayout()
        load_btn = PrimaryPushButton('加载矩阵', self)
        save_btn = PrimaryPushButton('保存修改', self)

        # 设置按钮大小
        for btn in [load_btn, save_btn]:
            btn.setFixedWidth(200)
            btn.setFixedHeight(40)

        load_btn.clicked.connect(self.load_matrix)
        save_btn.clicked.connect(self.save_matrix)
        btn_layout.addWidget(load_btn)
        btn_layout.addWidget(save_btn)
        layout.addLayout(btn_layout)

    def toggle_obstacle(self, row, col):
        item = self.matrix_editor.item(row, col)
        if item:
            current_value = int(item.text())
            new_value = 1 if current_value == 0 else 0
            item.setText(str(new_value))
            item.setBackground(Qt.black if new_value == 1 else Qt.white)
            item.setForeground(Qt.darkRed if new_value == 1 else Qt.black)  # 使用深红色

    def load_matrix(self):
        """加载矩阵文件到编辑器"""
        try:
            current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            matrix_file = os.path.join(current_dir, "data", "generated_matrix.txt")

            if not os.path.exists(matrix_file):
                InfoBar.warning(
                    title='警告',
                    content='请先生成矩阵',
                    parent=self
                )
                return

            # 读取矩阵数据
            with open(matrix_file, 'r') as f:
                # 读取第一行获取矩阵尺寸
                rows, cols = map(int, f.readline().strip().split())
                # 读取矩阵数据，注意每个字符之间有空格
                matrix = []
                for line in f:
                    # 分割每行的字符，处理空格分隔的字符
                    row = [1 if c == '@' else 0 for c in line.strip().split()]
                    matrix.append(row)

            # 设置表格尺寸
            self.matrix_editor.setRowCount(rows)
            self.matrix_editor.setColumnCount(cols)

            # 计算适合的单元格大小
            available_width = 1000
            available_height = 700

            cell_width = min(available_width // cols, 60)
            cell_height = min(available_height // rows, 60)
            cell_size = min(cell_width, cell_height)

            # 设置单元格大小
            for i in range(cols):
                self.matrix_editor.setColumnWidth(i, cell_size)
            for i in range(rows):
                self.matrix_editor.setRowHeight(i, cell_size)

            # 调整窗口大小
            table_width = cols * cell_size + 50
            table_height = rows * cell_size + 50
            self.matrix_editor.setMinimumSize(min(table_width, available_width),
                                              min(table_height, available_height))
            window_width = min(table_width + 150, 1200)
            window_height = min(table_height + 200, 900)
            self.resize(window_width, window_height)

            # 填充数据
            for i in range(rows):
                for j in range(cols):
                    item = QTableWidgetItem(str(matrix[i][j]))
                    item.setTextAlignment(Qt.AlignCenter)
                    # 设置背景色和文字颜色
                    if matrix[i][j] == 1:
                        item.setBackground(Qt.black)
                        item.setForeground(Qt.white)
                    else:
                        item.setBackground(Qt.white)
                        item.setForeground(Qt.black)
                    self.matrix_editor.setItem(i, j, item)

            InfoBar.success(
                title='成功',
                content=f'矩阵加载成功 ({rows}x{cols})',
                parent=self
            )

        except Exception as e:
            InfoBar.error(
                title='错误',
                content=f'加载矩阵失败: {str(e)}',
                parent=self
            )

    def save_matrix(self):
        """保存矩阵到generated_matrix.txt"""
        try:
            rows = self.matrix_editor.rowCount()
            cols = self.matrix_editor.columnCount()

            if not rows or not cols:
                InfoBar.warning(
                    title='警告',
                    content='没有要保存的矩阵数据',
                    parent=self
                )
                return

            current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            matrix_file = os.path.join(current_dir, "data", "generated_matrix.txt")

            with open(matrix_file, 'w') as f:
                # 写入矩阵尺寸
                f.write(f"{rows} {cols}\n")
                # 写入矩阵数据，确保字符之间有空格
                for i in range(rows):
                    row = []
                    for j in range(cols):
                        item = self.matrix_editor.item(i, j)
                        value = '@' if int(item.text()) == 1 else '.'
                        row.append(value)
                    # 用空格连接字符
                    f.write(' '.join(row) + '\n')

            InfoBar.success(
                title='成功',
                content=f'矩阵已保存 ({rows}x{cols})',
                parent=self
            )

        except Exception as e:
            InfoBar.error(
                title='错误',
                content=f'保存矩阵失败: {str(e)}',
                parent=self
            )
